package mylibrary.thread.FileDigest;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.sql.Timestamp;

import org.apache.commons.codec.binary.Hex;

public class FileDigestThread implements Runnable{

	String fileName = null;
	Test test = null;
	
	public FileDigestThread(String fileName, Test mainThread) {
		this.fileName = fileName;
		this.test = mainThread;
	}
	
	
	public void run() {
		
		System.out.println(fileName + " - Start: " + new Timestamp(System.currentTimeMillis()));
		
		try {
			InputStream in = new FileInputStream(fileName);
			MessageDigest sha = MessageDigest.getInstance("SHA");
			DigestInputStream din = new DigestInputStream(in, sha);

			int b = 0;
			while((b=in.read()) != -1) ;
			din.close();
			
			byte[] digest = sha.digest();
			StringBuffer result = new StringBuffer(fileName);
			result.append(": ");
			
			for(int i=0; i<digest.length; i++) {
				result.append(digest[i] + " ");
			}
			
			//System.out.println(result.toString());
			//System.out.println(Hex.encodeHex(digest));
			test.receiveResult(new String(Hex.encodeHex(digest)));
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(fileName + " - End: " + new Timestamp(System.currentTimeMillis()));
	}

}
